<?php
namespace app\index\controller;

use app\common\model\User;
use app\common\model\Rec;

class Login extends Common
{
    public function index() {
        return $this->fetch();
    }

    /**
     * 登录
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login() {
        $this->checkAlreadyLogin();
        if (isAjaxPost()) {
            $tel = input('post.tel', '', 'trim');
            $pwd = input('post.password', '', 'trim');
            if (!checkTel($tel)) {
                return $this->jsonError('手机号格式错误');
            }
            if (empty($pwd)) {
                return $this->jsonError('请输入密码');
            }
            $userModel = new User();
            $info = $userModel->findUser(['tel'=>$tel, 'password'=>md5($pwd)]);
            if (empty($info)) {
                return $this->jsonError('密码错误');
            }
            if ($info['locks'] == 1) {
                return $this->jsonError('该帐号已被管理员锁定，如有疑问请联系客服人员');
            }

            session('user', $info);
            $redirect_uri = session('redirect_uri');
            session('redirect_uri', '');
            return $this->jsonSuccess('登录成功', !empty($redirect_uri) ? $redirect_uri : '');
        }

        return $this->fetch();
    }

    /**
     * 已经登录
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function checkAlreadyLogin() {
        if ($this->checkLogin()) {
            if (isAjaxPost()) {
                return $this->jsonSuccess('您已经登录过了');
            } else {
                layerExit('您已经登录过了', url('index/index'));
            }
        }
    }

    /**
     * 注册
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function register() {
        if (input('handel') != 1) {
            $this->checkAlreadyLogin();
        }
        if (isAjaxPost()) {
            $data = [
                'name' => input('post.name', '', 'trim'),
                'tel' => input('post.tel', '', 'trim'),
                'password' => input('post.password', '', 'trim'),
                'add_time' => time(),
                'img' => config('default_user_img'),
                'is_add' => input('post.is_add', 0, 'intval'),
                'referee_code' => input('post.referee_code'),

            ];
            $confirm_password = input('post.confirm_password', '', 'trim');
            $code = input('post.code', '', 'trim');
            $validate = new \app\system\validate\User();
            if (!$validate->check($data, '', 'add')) {
                return $this->jsonError($validate->getError());
            }
            if ($data['password'] != $confirm_password) {
                return $this->jsonError('两次登录密码输入不一致');
            }
           
            if (input('post.pay_password') != input('post.confirm_pay_password')) {
                return $this->jsonError('两次支付密码输入不一致');
            }
            //邀请人
            $model = new User();
            //校验验证码
            // $res = checkCode($data['tel'], $code);
            // if ($res !== true) {
            //     return $this->jsonError($res);
            // }

            //插入
            $data['password'] = md5($data['password']);
            $data['pay_password'] = md5(input('post.confirm_pay_password'));
            $data['code'] = generate(6);
           
            $parent = $model->where(['code' => $data['referee_code']])->field('id,code,name,is_active')->find();

            if (empty($parent)) {
                return $this->jsonError('推荐人不存在');
            }
            if(!$parent['is_active']){
                return $this->jsonError('推荐人未激活');
            }
            $is = $model->where(['tel' => $data['tel']])->field('id,code,name')->find();
            if ($is) {
                return $this->jsonError('手机号已存在');
            }
            $data['referee_id'] = $parent['id'];
            $data['pid'] = $parent['id'];
            if ($uid = $model->insertGetId($data)) {
                $data['id'] = $uid;
                //生成邀请二维码
                // saveQrcode($data);
                if (input('handel') != 1) {
                    session('user', $model->findUser(['id' => $uid]));
                }
                $redirect_uri = session('redirect_uri');
                session('redirect_uri', '');
                //记录推荐关系
                $res = Rec::recommend($uid, $data['code'], $data['referee_code']);
                if ($res !== true) {
                    return $this->jsonError('关系记录失败');;
                }
                return $this->jsonSuccess('注册成功', !empty($redirect_uri) ? $redirect_uri : '');
            } else {
                return $this->jsonError('注册失败');
            }
        }
        return $this->fetch();
    }

    /**
     * 检查手机号是否注册
     * @param $tel
     * @return \think\response\Json
     */
    public function checkRegister($tel) {
        !isAjaxPost() && die();
        if (!checkTel($tel)) {
            return $this->jsonError('手机号格式错误');
        }

        $model = new User();
        if ($model->where(['tel'=>$tel])->count() > 0) {
            return $this->jsonError('手机号已经存在');
        } else {
            return $this->jsonSuccess('');
        }
    }

    /**
     * 忘记密码
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function forgot_password() {
        $this->checkAlreadyLogin();
        if (isAjaxPost()) {
            $tel = input('post.tel', '', 'trim');
            $code = input('post.code', '', 'trim');
            $pwd = input('post.password', '', 'trim');
            $confirm_password = input('post.confirm_password', '', 'trim');
            if (!checkTel($tel)) {
                return $this->jsonError('手机号格式错误');
            }
            if (empty($code)) {
                return $this->jsonError('请输入验证码');
            }
            if (empty($pwd)) {
                return $this->jsonError('请输入密码');
            }
            if ($pwd != $confirm_password) {
                return $this->jsonError('两次密码输入不一致');
            }

            $res = checkCode($tel, $code);
            if ($res !== true) {
                return $this->jsonError($res);
            }

            $model = new User();
            if ($model->where(['tel'=>$tel])->setField('password', passmd($pwd)) !== false) {
                return $this->jsonSuccess('操作成功');
            } else {
                return $this->jsonError('操作失败');
            }
        }
        return $this->fetch();
    }


}